<template>
  <i v-if="$slots.default" :class="[yqNs.b(), elNs.b()]" :style="[iconStyle, props.style]">
    <slot />
  </i>
  <i v-else-if="iconType === IconType.COMPONENT_NAME" :class="[yqNs.b(), elNs.b()]" :style="[iconStyle, props.style]">
    <component :is="src"></component>
  </i>
  <div v-else-if="iconType === IconType.IMG" :class="[yqNs.b(), elNs.b()]" :style="[imgContainerStyle, props.style]">
    <img :class="yqNs.e('img')" :src="props.src" />
  </div>
  <i v-else :class="[yqNs.b(), elNs.b(), props.src]" :style="[iconStyle, props.style]"></i>
</template>
<script setup lang="ts" name="YqIcon">
import { computed, CSSProperties, StyleValue } from "vue";
import { useNamespace } from "element-plus";
import { addUnit } from "element-plus/es/utils/dom/style";
import { yqNamespace } from "@/yqSrc/bem";
import { YqIconProps, IconType, COMPONENT_ICON_NAME_PREFIX as ICON_COMPONENT_NAME_PREFIX, IMG_ICON_PREFIX } from "./types";
const yqNs = useNamespace("icon", yqNamespace);
const elNs = useNamespace("icon");

const props = withDefaults(defineProps<YqIconProps>(), {});

const src = computed(() => {
  return props.src && props.src.toLowerCase();
});

// 图标类型
const iconType = computed(() => {
  const srcValue = src.value;
  if (!srcValue) {
    return IconType.COMPONENT;
  } else if (isIconComponentName(srcValue)) {
    return IconType.COMPONENT_NAME;
  } else if (isImgIcon(srcValue)) {
    return IconType.IMG;
  } else {
    return IconType.CLASS;
  }
});

// 图标组件名称
const isIconComponentName = (src: string) => {
  for (const srcPrefix of ICON_COMPONENT_NAME_PREFIX) {
    if (src.startsWith(srcPrefix)) {
      return true;
    }
  }
  return false;
};

// 图像图标
const isImgIcon = (src: string) => {
  for (const srcPrefix of IMG_ICON_PREFIX) {
    if (src.startsWith(srcPrefix)) {
      return true;
    }
  }
  return false;
};

// 组件图标，class图标样式
const iconStyle = computed<StyleValue | undefined>(() => {
  if (!props.size && !props.color) {
    return;
  }
  let style: CSSProperties = {};
  if (props.size || props.size == 0) {
    style.fontSize = addUnit(props.size);
  }
  if (props.color) {
    style["--color"] = props.color;
  }
  return style;
});

// 图像图标样式
const imgContainerStyle = computed<StyleValue | undefined>(() => {
  if (!props.size) {
    return;
  }
  let style: CSSProperties = {
    display: "inline-block",
    overflow: "hidden"
  };
  if (props.size || props.size == 0) {
    style.width = addUnit(props.size);
    style.height = style.width;
  }
  return style;
});
</script>
